﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using ExamSelf.Web.Models;

namespace ExamSelf.Web.Controllers
{

    [ExamSelf.Web.Controllers.LoginController.RequiresAuthentication]
    public class ManageController : Controller
    {
        //
        // GET: /Manage/
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult QuestionManage()
        {
            return View();
        }

        //public JsonResult GetQuestionList()
        //{
        //    var request = new EasyUIGridRequest(HttpContext);
        //    EasyUIGrid grid = new EasyUIGrid();
        //    using (ExamSelfDbContext db = new ExamSelfDbContext())
        //    {
        //        var result = db.Questions.OrderByDescending(t => t.Id);
        //        grid.total = result.Count();
        //        grid.rows = result.Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
        //    }
        //    return this.Json(grid);
        //}

        public JsonResult GetQuestionList(string worktype, string questiontype,string content)
        {
            var request = new EasyUIGridRequest(HttpContext);
            EasyUIGrid grid = new EasyUIGrid();
            using (ExamSelfDbContext db = new ExamSelfDbContext())
            {
                var result = from i in db.Questions select i;
                if (!string.IsNullOrEmpty(worktype))
                {
                    result = result.Where(i => i.WorkType.Contains(worktype));
                }
                if (!string.IsNullOrEmpty(questiontype))
                {
                    int type = Convert.ToInt32(questiontype);

                    result = result.Where(i =>(int) i.QuestionType== type);
                }
                if (!string.IsNullOrEmpty(content))
                {
                    result = result.Where(i => i.Content.Contains(content));
                }
                result = result.OrderByDescending(t => t.Id);
                grid.total = result.Count();
                grid.rows = result.Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            }
            return this.Json(grid);
        }

        public ActionResult CreateQuestion()
        {
            return View();
        }

        /// <summary>
        /// 保存题目
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> SaveQuestion(SaveQuestion question)
        {
            using (ExamSelfDbContext db = new ExamSelfDbContext())
            {
                if (question.QuestionInfo.Id == 0)
                {
                    db.Questions.Add(question.QuestionInfo);
                    await db.SaveChangesAsync();
                    foreach (var op in question.OptionsInfoes)
                    {
                        op.QuestionID = question.QuestionInfo.Id;
                        db.Options.Add(op);
                    }
                    var rowCount = await db.SaveChangesAsync();
                    return this.Json(new { result = rowCount > 0 });
                }
                else
                {
                    //先删除现有选项
                    db.Database.ExecuteSqlCommand("DELETE FROM dbo.OptionsInfoes WHERE QuestionID=@QID", new SqlParameter("@QID", question.QuestionInfo.Id));
                    //db.Questions.Attach(question.QuestionInfo);
                    question.QuestionInfo.ModifyDate = DateTime.Now;
                    db.Entry(question.QuestionInfo).State = EntityState.Modified;
                    db.Options.AddRange(question.OptionsInfoes);
                    var rowCount = await db.SaveChangesAsync();
                    return this.Json(new { result = rowCount > 0 });
                }
            }
        }

        /// <summary>
        /// 删除问题
        /// </summary>
        /// <param name="QID"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> DeleteQuestion(int? QID)
        {
            if (QID.HasValue)
            {
                using (ExamSelfDbContext db = new ExamSelfDbContext())
                {
                    var rowCount = db.Database.ExecuteSqlCommand("DELETE FROM dbo.QuestionInfoes WHERE Id=@Id", new SqlParameter("@Id", QID));
                    db.Database.ExecuteSqlCommand("DELETE FROM dbo.OptionsInfoes WHERE QuestionID=@QID", new SqlParameter("@QID", QID));
                    return this.Json(new { result = rowCount > 0 });
                }
            }
            else
            {
                return this.Json(new { result = false });
            }
        }

        /// <summary>
        /// 获取问题
        /// </summary>
        /// <param name="QID"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetQuestion(int QID)
        {
            using (ExamSelfDbContext db = new ExamSelfDbContext())
            {
               Models.SaveQuestion entity=new SaveQuestion();
                var ques = db.Questions.SingleOrDefault(t => t.Id == QID);
                if (ques != null)
                    entity.QuestionInfo = ques;
                var options = db.Options.Where(t => t.QuestionID == QID).ToList();
                entity.OptionsInfoes = options;
                return this.Json(entity,JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 上传文件接口
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <param name="type"></param>
        /// <param name="lastModifiedDate"></param>
        /// <param name="size"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public ActionResult Process(string id, string name, string type, string lastModifiedDate, int size, HttpPostedFileBase file)
        {
            string filePathName = String.Empty;
            string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, "Upload");
            if (Request.Files.Count == 0)
            {
                return Json(new { jsonrpc = 2.0, error = new { code = 102, message = "保存失败" }, id = "id" });
            }
            try
            {
                //判断文件夹是否存在
                if (!Directory.Exists(localPath))
                {
                    Directory.CreateDirectory(localPath);
                }
                filePathName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + "_" + name;
                file.SaveAs(localPath + "\\" + filePathName);
            }
            catch (Exception)
            {
                return Json(new { jsonrpc = 2.0, error = new { code = 103, message = "保存失败" }, id = "id" });
            }

            return Json(new
            {
                jsonrpc = "2.0",
                id = "id",
                filePath = "/Upload" + "/" + filePathName
            });
        }
    }
}